import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ApiResponse, BannerItem, GoodsItem, HotGoods, Brand, HomeProduct, Special } from '@/types/data'

export default defineStore('home', {
  state: () => {
    return {
      // 轮播图数据
      bannerList: [] as BannerItem[],
      // 新鲜好物数据
      newGoodsList: [] as GoodsItem[],
      // 人气推荐
      hotGoodList: [] as HotGoods[],
      // 热门品牌
      brandList: [] as Brand[],
      // 居家美食
      productList: [] as HomeProduct[],
      // 最新专题
      specialList: [] as Special[],
    }
  },
  getters: {},
  actions: {
    // fetch轮播图数据
    async fetchBannerList() {
      try {
        const res = await request.get<ApiResponse<BannerItem[]>>('/home/banner')
        if (res.data.result?.length) {
          this.bannerList = res.data.result
        }
      } catch (error) {
        console.error(error)
      }
    },
    // fetch新鲜好物数据
    async fetchNewGoodsList() {
      try {
        const res = await request.get<ApiResponse<GoodsItem[]>>('/home/new')
        if (res.data.result?.length) {
          this.newGoodsList = res.data.result
        }
      } catch (error) {
        console.error(error);
      }
    },
    // fetch人气好物数据
    async fetchHotGoodList() {
      try {
        const res = await request.get<ApiResponse<HotGoods[]>>('/home/hot')
        if (res.data.result?.length) {
          this.hotGoodList = res.data.result
        }
      } catch (error) {
        console.error(error);

      }
    },
    // fetct热门品牌数据
    async fetchBrandList() {
      try {
        const res = await request.get<ApiResponse<Brand[]>>('/home/brand')
        if (res.data.result?.length) {
          this.brandList = res.data.result
        }
      } catch (error) {
        console.error(error);
      }
    },
    // fetct居家美食数据
    async fetchProductList() {
      try {
        const res = await request.get<ApiResponse<HomeProduct[]>>('/home/goods')
        if (res.data.result?.length) {
          this.productList = res.data.result
        }
      } catch (error) {
        console.error(error);
      }
    },
    // fetct最新专题数据
    async getSpecialList() {
      const res = await request.get<ApiResponse<Special[]>>('/home/special')
      if (res.data.result?.length) {
        this.specialList = res.data.result
      }
    },
  }
})   